from django.shortcuts import redirect, render, HttpResponse, reverse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from web.forms.wiki import WikiModeForm
from web import models
from utils.tencent.tencent_cos import upload_cos_image
from utils.encrypt import uid


def wiki(request, project_id):
    """wiki首页与预览文章"""
    wiki_id = request.GET.get("wiki_id")
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, "wiki.html")

    wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, "wiki.html", {"wiki_obj": wiki_obj})


def wiki_add(request, project_id):
    """wiki添加"""
    if request.method == 'GET':
        form = WikiModeForm(request)
        return render(request, "wiki_form.html", {"form": form})

    form = WikiModeForm(request, data=request.POST)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project
        form.save()

        url = reverse("wiki", kwargs={"project_id": project_id})
        return redirect(url)

    return render(request, "wiki_form.html", {"form": form})


def init_catalog(request, project_id):
    """wiki目录"""
    # 获取当前wiki下的所有文章的目录
    data_list = models.Wiki.objects.filter(project=request.tracer.project).values("id", "title", "parent_id").order_by(
        "depth", "id")
    return JsonResponse({"status": True, "data": list(data_list)})


def wiki_delete(request, project_id, wiki_id):
    """删除wiki"""
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    url = reverse("wiki", kwargs={"project_id": project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """删除wiki"""
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if request.method == 'GET':
        form = WikiModeForm(request, instance=wiki_obj)
        return render(request, "wiki_form.html", {"form": form})

    form = WikiModeForm(request, instance=wiki_obj, data=request.POST)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.tracer.project
        form.save()

        url = reverse("wiki", kwargs={"project_id": project_id})
        next_url = "{0}?wiki_id={1}".format(url,wiki_id)
        return redirect(next_url)

    return render(request, "wiki_form.html", {"form": form})


@csrf_exempt
def wiki_upload(request, project_id):
    """markdown上传图片"""
    # print(request.FILES)
    # 通知markdwon是否上传图片成功
    result = {
        "success": 0,
        "message": None,
        "url": None,
    }

    image_obj = request.FILES.get("editormd-image-file")
    if not image_obj:
        result['message'] = "文件不存在"
        return JsonResponse(result)
    ext = image_obj.name.rsplit(".")[-1]
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone), ext)
    image_url = upload_cos_image(
        request.tracer.project.bucket,
        request.tracer.project.region,
        key,
        image_obj
    )

    # 通知markdwon是否上传图片成功
    result["success"] = 1
    result["url"] = image_url

    return JsonResponse(result)
